from gi.repository import GObject, Gtk, Gst, Gt

class PlayerBackendRecorder(GObject.GObject, Gt.PlayerBackend):
    __gtype_name__ = "PlayerBackendRecorder"
    @GObject.Property(type=str)
    def uri(self):
        return self._uri
    @uri.setter
    def uri(self, value):
        self._uri = value
    
    @GObject.Property(type=float)
    def volume(self):
        return self._volume
    @volume.setter
    def volume(self, value):
        self._volume = value
    
    @GObject.Property(type=bool, default=False)
    def playing(self):
        return self._playing
    @playing.setter
    def playing(self, value):
        self._playing = value
        if self._playing:
            self.start()
        else:
            self.stop()

    @GObject.Property(type=float)
    def buffer_fill(self):
        return self._buffer_fill
    @buffer_fill.setter
    def buffer_fill(self, value):
        self._buffer_fill = value

    def cb_uri_change(self, foo, bar):
        print (self.get_property("uri"))

    def start(self):
        self._playbin.set_state(Gst.State.PLAYING)
    def stop(self):
        self._playbin.set_state(Gst.State.NULL)

    def cb_gst_message(self, bus, msg, data=None):
        print("inhere")
        if msg == Gst.MessageType.BUFFERING:
            perc = msg.parse()
            if perc < 100:
                self._playbin.set_state(Gst.State.PAUSED)
            else:
                self._playbin.set_state(Gst.State.PLAYING)
            self.set_property("buffer-fill", perc/100.0)


    def __init__(self):
        self._uri = ""
        self._volume = 1.0
        self._playing = False
        self._buffer_fill = 1.0
        self._widget = None

        GObject.GObject.__init__(self)
        self.connect("notify::uri", self.cb_uri_change)

        Gst.init_check(None)
        self._playbin = Gst.ElementFactory.make("playbin")
        self._videosink = Gst.ElementFactory.make("gtksink")
        self._bus = self._playbin.get_bus()
        self._bus.add_watch(0, self.cb_gst_message)

        builder = Gtk.Builder()
        builder.add_from_file("/home/grindhold/git/gnome-twitch-player-gstreamer-recorder/player-backend-gstreamer-recorder.ui")
        self._widget = builder.get_object("recordbox")

        self._widget.add(self._videosink.get_property("widget"))
        self._playbin.set_property("video-sink", self._videosink)

        self.bind_property("uri", self._playbin, "uri")
        self.bind_property("volume", self._playbin, "volume")


    def do_get_widget(self):
        self.playing = True
        print (self.get_property("uri"))
        return self._widget
